package com.woniu.postbar.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.common.constant.PostBarConstant;
import com.woniu.common.entity.Result;
import com.woniu.postbar.mapper.PostLikeMapper;
import com.woniu.postbar.pojo.PostLike;
import com.woniu.postbar.service.IPostLikeService;
import com.woniu.postbar.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wu
 * @since 2023-05-20
 */
@Service
public class PostLikeServiceImpl extends ServiceImpl<PostLikeMapper, PostLike> implements IPostLikeService {

    @Autowired
    private RedisService redisService;

    @Override
    public Result<Object> likePost(Integer postId, Integer userId) {
        // 查询Redis是否已经存储为喜欢
        Integer status = redisService.getLikeStatus(postId, userId);
        if (status == PostBarConstant.LIKE_STATUS_LIKE){
            // 已经存在点赞
            return Result.error(PostBarConstant.USER_LIKE_RESULT_SUCCESS);
        }
        // 不存在或者之前是取消喜欢
        try {
            redisService.saveLikedRedis(postId, userId);
            redisService.decrementLikedCount(postId, 1);
            return Result.ok(PostBarConstant.USER_LIKE_REDIS_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(PostBarConstant.USER_LIKE_REDIS_ERROR);
        }
    }

    @Override
    public Result<Object> dislikePost(Integer postId, Integer userId) {
        // 查询Redis是否已经存储为取消喜欢
        Integer status = redisService.getLikeStatus(postId, userId);
        if (status == PostBarConstant.LIKE_STATUS_UNLIKE){
            // 已经存在取消喜欢
            return Result.error(PostBarConstant.USER_LIKE_RESULT_CANCEL);
        }
        else if (status.equals(PostBarConstant.LIKE_STATUS_NO_EXIT)) {
            // 不存在取消喜欢，修改状态，增加0条
            redisService.unlikeFromRedis(postId, userId);
            redisService.decrementLikedCount(postId,0);
            return Result.error(PostBarConstant.USER_LIKE_REDIS_CANCEL_SUCCESS);
        }
        else{
            // 之前已经喜欢，则修改状态,并喜欢数-1
            try {
                redisService.unlikeFromRedis(postId, userId);
                redisService.decrementLikedCount(postId,-1);
                return Result.error(PostBarConstant.USER_LIKE_REDIS_CANCEL_SUCCESS);
            }catch (Exception e){
                e.printStackTrace();
                return Result.error(PostBarConstant.USER_LIKE_REDIS_CANCEL_ERROR);
            }
        }
    }
}
